<template>
  <BasicDrawer
    :destroyOnClose="true"
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    title="支付"
    width="620px"
    @close="onClose"
    :maskClosable="false"
  >
    <template #footer>
      <a-button @click="onClose">取消</a-button>
      <a-button type="primary" @click="onAffirm">确认支付</a-button>
    </template>
    <div class="card" style="width: 100%">
      <div class="c-title"> 支付明细 </div>

      <a-flex class="r-row" justify="space-between" align="center">
        <div class="r-label">商品金额</div>
        <div class="r-value">¥&nbsp;{{ getCartRetailAmount() }}</div>
      </a-flex>

      <a-flex class="r-row" justify="space-between" align="center">
<!--        <div class="r-label">{{ state.cartType === 'cardUpgrade' ? '折后价' : '折后金额' }}</div>-->
        <div class="r-label">折后金额</div>
        <div class="r-value">¥&nbsp;{{ getCartDiscountAfterAmount() }}</div>
      </a-flex>

      <a-flex class="r-row" justify="space-between" align="center">
        <div class="r-label">抵扣金额</div>
        <div>¥&nbsp;{{ round(state.discountAfterAmount || 0)?.toFixed(2) }}</div>
      </a-flex>

      <div style="border-bottom: 1px dashed #ccc; margin: 12px 0"></div>

      <a-flex class="r-row" justify="space-between">
        <div class="r-label">应付金额</div>
<!--        <div v-if="state.nums == '1'">¥&nbsp;{{ getCartPayableAmount(state.nums) }}</div>-->
        <div class="r-value2">¥&nbsp;{{ state.paymentCount || 0 }}</div>
      </a-flex>

      <div class="c-title" style="margin-top: 32px"> 支付方式 </div>

      <a-flex class="r-row" gap="middle" align="center">
        <div class="r-label"><span class="must">*</span>支付方式</div>
        <div class="data-group">
          <div
            :class="['use', 'cell', state.cashPayCode === o.value ? 'active' : 'tacit']"
            v-for="o in cashPayCodes"
            :key="o.value"
            @click="state.cashPayCode = o.value"
            >{{ o.label }}
          </div>
        </div>
      </a-flex>

      <a-flex class="r-row" gap="middle" align="center" style="position: relative">
        <div class="r-label"><span class="must">*</span>实付金额</div>
        <div>
          <div>
            <a-input-number
              v-model:value="state.totalFee"
              :min="0"
              :max="state.paymentCount"
              :precision="2"
              addon-after="元"
            />
          </div>
          <div class="hint" style="position: absolute" v-if="!isNil(state.totalFee)">
            欠款金额&nbsp;-{{ round(state.paymentCount - (state.totalFee || 0) || 0) }}元
          </div>
        </div>
      </a-flex>
    </div>
  </BasicDrawer>
</template>

<script setup>
  import { defineOptions, onMounted, reactive, inject, computed, watch, nextTick } from 'vue';

  import { useRouter } from 'vue-router';
  import { useMessage } from '@/hooks/web/useMessage';
  import { BasicDrawer, useDrawerInner, useDrawer } from '@/components/Drawer';
  import {
    shopCartRef,
    createCardUpgradeOrder,
    createShopOrder,
    getCartDiscountAfterAmount,
    getCartMoneyDeductionAmount,
    getCartPayableAmount,
    getCartRetailAmount,
  } from '@/views/cashier/cart.js';
  import { cashPayCodes } from '@/api/ds.js';
  import { isNil, round } from '@/api/util.js';

  const router = useRouter();
  const { createMessage, createConfirm } = useMessage();

  defineOptions({ name: 'CashierPayment' });

  const state = reactive({
    cashPayCode: null,
    memberCode: null,
    totalFee: null,
    paymentCount: null,
    getCartPayableAmountFn: null,
    // 抵扣金额
    discountAfterAmount: null,
    nums: null
  });

  const [registerDrawer, { closeDrawer, changeLoading }] = useDrawerInner(
    async ({ memberCode, cartType, quoteCardItem, getCartPayableAmount: getCartPayableAmountFn, updateDefaultTotalFee, discountAfterAmount}) => {
      // console.log(num, '09876543')
      // state.nums = num;
      state.cashPayCode = null;
      state.memberCode = memberCode;
      state.totalFee = getCartPayableAmount();

      if (updateDefaultTotalFee) {
        state.totalFee = updateDefaultTotalFee()
      }

      state.paymentCount = state.totalFee;
      // console.log('open', state.totalFee);

      state.cartType = cartType;
      state.quoteCardItem = quoteCardItem;

      state.getCartPayableAmountFn = getCartPayableAmountFn;

      state.discountAfterAmount = discountAfterAmount ?? getCartMoneyDeductionAmount();
    },
  );
  
  // const paymentCount = computed(() => {
  //   return state?.getCartPayableAmountFn?.() ?? (shopCartRef.value?.reduce((acc, item) => {
  //     return acc + (item.discountAfterAmount - item.deductionAmount9);
  //   }, 0));
  // });

  onMounted(() => {
    sessionStorage.removeItem('masterOrderSn');
  });

  async function onAffirm() {
    const { memberCode, cashPayCode, totalFee } = state;

    if (!cashPayCode) {
      return createMessage.error('请选择支付方式');
    }

    if (memberCode === '-1') {
      if (Math.abs(state.paymentCount - totalFee) > 0.0001) {
        return createMessage.error('散客不允许欠款收银');
      }
    }

    createConfirm({
      content: '您确要支付订单吗',
      onOk: async () => {
        try {
          const debtFee = round(state.paymentCount - totalFee);

          changeLoading(true);
          const { cartType, quoteCardItem } = state;
          let masterOrderSn = null;

          if (cartType === 'cardUpgrade') {
            ({ masterOrderSn } = await createCardUpgradeOrder({
              memberCode,
              cashPayCode,
              debtFee,
              totalFee,
              quoteCardItem,
              sourceCode: '21',
              referer: 'PC端',
              errorFn: (msg) => createMessage.error(msg),
            }));
          } else {
            ({ masterOrderSn } = await createShopOrder({
              memberCode,
              cashPayCode,
              debtFee,
              totalFee,
              sourceCode: '21',
              referer: 'PC端',
            }));
          }

          createMessage.success('订单已支付');
          router.push(`/report/order-list?masterOrderSn=${masterOrderSn}`);
        } finally {
          changeLoading(false);
        }
      },
    });
  }

  const { onSavePendingOrder } = inject('onSavePendingOrder');

  function onClose() {
    if (state.cartType !== 'cardUpgrade') {
      onSavePendingOrder();
    } else {
      closeDrawer()
    }
  }
</script>
<style lang="less" scoped>
  .card {
    height: 100%;
    padding: 16px;

    .c-title {
      padding: 32px 0 6px 0;
      color: #091f3d;
      font-size: 15px;
      font-weight: 600;
    }

    .c-title:first-child {
      padding-top: 8px;
    }

    .r-row {
      margin: 12px 0;
    }

    .r-label {
      font-weight: 400;
      font-size: 16px;
      color: #666666;
    }

    .r-value {
      font-weight: 400;
      font-size: 14px;
      color: #666666;
    }

    .r-value2 {
      font-weight: 500;
      font-size: 16px;
      color: #eb6485;
    }

    .hint {
      font-weight: 400;
      font-size: 13px;
      color: #666666;
      margin-top: 4px;
    }
  }
</style>

<style lang="less" scoped>
  .data-group {
    display: flex;
    flex-flow: row wrap;
    align-items: center;
    cursor: pointer;
    gap: 8px 12px;

    .cell {
      padding: 4px 20px;
      border-radius: 4px;
      font-size: 14px;
      font-weight: 400;
    }

    .tacit {
      border: 1px solid #e0e5ec;
      color: #091f3d;
    }

    .active {
      border: 1px solid @primary-color;
      background-color: @primary-color;
      color: #fff;
    }
  }
</style>
